﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using CRMFramework;
using CRMEntity;
using CRMBiz;
using CRMWeb.Utilities;
using CRMWeb.Utilities.Context;

namespace CRMWeb.Pages
{
    public partial class Login : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            var entity = CmsMemberHandler.Login(txtUser.Text, Utilities.CryptographyHelper.EncodePassword(txtPassword.Text));
            if (entity != null)
            {
                int status = CheckIPAddress(txtUser.Text, Utilities.CryptographyHelper.EncodePassword(txtPassword.Text));
                if (status == 0)
                {
                    lblLoginInfo.Text = "Invalid IP address : " + System.Web.HttpContext.Current.Request.UserHostAddress;
                }
                else
                {
                    CMSContext.AuthenticateUser(txtUser.Text, false);
                    Response.Redirect("/Pages/DashBoard.aspx");
                }
            }
            else
            {
                lblLoginInfo.Text = "Invalid username or password";
            }
        }

        //Check IP Address:
        public int CheckIPAddress(string username, string password)
        {
            int intReturnValue = 0;
            try
            {
                intReturnValue = CmsMemberHandler.GetIPAddress(username,password);
            }
            catch (Exception ex)
            {
                ErrorHandler.saveErrorLog(ex,CMSContext.CurrentUser.MemberName);
            }
            return intReturnValue;
        }
    }
}